package com.yuliang.basic;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Properties;

public class BeanFactory {

    private static Properties env = new Properties();

    static {
        //getResourceAsStream 方法是 Java 中 Class 类的一个方法。它用于获取给定路径的资源文件的输入流。
        InputStream resourceAsStream = BeanFactory.class.getResourceAsStream("/applicationContext.properties");
        try {
            //第⼆步 ⽂件内容 封装 Properties集合中 key value
            env.load(resourceAsStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
//    public static UserService getUserService() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
//
////        Class<?> clazz = Class.forName("com.yuliang.basic.UserServiceImpl");
//        //读取配置文件解耦合
//        Class<?> clazz = Class.forName(env.getProperty("userService"));
//        UserService UserService = (UserService) clazz.newInstance();
//        return UserService;
//    }
//
//    public static UserDao getUserDao() {
//        UserDao UserDao = null;
//        try {
//            Class<?> clazz = Class.forName(env.getProperty("userDao"));
//            UserDao = (UserDao)clazz.newInstance();
//        } catch (ClassNotFoundException e) {
//            throw new RuntimeException(e);
//        } catch (InstantiationException e) {
//            throw new RuntimeException(e);
//        } catch (IllegalAccessException e) {
//            throw new RuntimeException(e);
//        }
//        return UserDao;
//    }

    public static Object getBean(String key){
        Object object = null;
        try{
            Class<?> clazz = Class.forName(env.getProperty(key));
            object = clazz.newInstance();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return object;
    }
}
